import 'dart:io';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:top_foundation/component/wrap.dart';
import 'package:top_foundation/utils/ex/image.dart';
import 'package:top_foundation/utils/theme/theme.dart';
import 'package:whale/helper/utils/media_picker.dart';
import 'package:whale/helper/utils/util.dart';

class AddPickersView extends StatefulWidget {
  const AddPickersView({super.key});

  @override
  State<AddPickersView> createState() => _AddPickersViewState();
}

class _AddPickersViewState extends State<AddPickersView> {
  late final List<MediaModel> list = [];
  late int maxCount = 9;
  double _moveSize = 100.r;
  final int column = 3;

  int _focusIndex = -1;
  MediaModel? _focusModel;
  Offset? _start;
  Offset? _move;
  final _deleteKey = GlobalKey();
  Rect? _deleteRect;

  void pickImages() async {
    final data = await MediaPicker.pickImages(maxCount: maxCount - list.length);

    list.addAll(data.map((e) => MediaModel(media: e)));
    setState(() {});
  }

  void remove(int index) {
    list.removeAt(index);
    setState(() {});
  }

  void preview(int index) {
    MediaPicker.previewMedias(
        imageMedias: list.map((e) => e.media).toList(), initIndex: index);
  }

  void onLongPressStart(LongPressStartDetails details) {
    Get.log('onPanStart');
    _start = details.globalPosition;
    _focusIndex = list.indexWhere((element) => element.rect.contains(_start!));

    if (_focusIndex >= 0) {
      _focusModel = list[_focusIndex];
      _moveSize = _focusModel!.rect.size.width * 1.1;
    }
    _move = Offset(_focusModel!.rect.left - list.first.rect.left,
        _focusModel!.rect.top - list.first.rect.top);
    setState(() {});
  }

  void onLongPressMoveUpdate(LongPressMoveUpdateDetails details) {
    if (_focusIndex == -1) return;
    final next = details.localPosition;
    if (_deleteRect == null) {
      getDeleteRect();
    }
    _move = Offset(next.dx - _start!.dx + _focusModel!.rect.left,
        next.dy - _start!.dy + _focusModel!.rect.top);
    setState(() {});
  }

  void onLongPressEnd(LongPressEndDetails details) {
    if (_focusIndex == -1) return;

    if (isMoveCanDelete()) {
      list.remove(_focusModel);
      _focusModel = null;
    }
    _focusIndex = -1;
    _start = null;
    _move = null;
    setState(() {});
  }

  bool isMoveCanDelete() {
    if (_deleteRect == null) return false;
    return _move!.dy + _moveSize + _focusModel!.rect.top > _deleteRect!.top;
  }

  void getDeleteRect() {
    final box = _deleteKey.currentContext?.findRenderObject() as RenderBox?;
    if (box == null) return;

    final orign = box.localToGlobal(Offset.zero);
    _deleteRect =
        Rect.fromLTWH(orign.dx, orign.dy, box.size.width, box.size.height);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Stack(
          children: [
            Padding(
              padding: EdgeInsets.only(bottom: 10.r),
              child: GestureDetector(
                onLongPressStart: onLongPressStart,
                onLongPressMoveUpdate: onLongPressMoveUpdate,
                onLongPressEnd: onLongPressEnd,
                child: IWrap(
                  column: column,
                  spacing: 10.r,
                  runSpacing: 10.r,
                  itemBuilder: (context, index) {
                    return AspectRatio(
                      aspectRatio: 1,
                      child: index >= list.length
                          ? AddImageItemView(
                              onTap: pickImages,
                            )
                          : (_focusIndex == index
                              ? const SizedBox()
                              : ImageItemView(
                                  media: list[index],
                                  onTap: () => preview(index),
                                )),
                    );
                  },
                  itemCount: min(list.length + 1, maxCount),
                ),
              ),
            ),
            if (_focusIndex >= 0)
              Positioned(
                left: _move?.dx,
                top: _move?.dy,
                width: _moveSize,
                height: _moveSize,
                child: Image.file(
                  File(
                    _focusModel!.media.path!,
                  ),
                  fit: BoxFit.cover,
                ),
              )
          ],
        ),
        if (_focusIndex >= 0)
          Opacity(
            opacity: 0.5,
            child: Container(
              key: _deleteKey,
              color: Colors.red,
              height: 50.r,
              width: double.infinity,
              padding: EdgeInsets.symmetric(horizontal: 12.r),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.delete,
                    color: Colors.white,
                    size: 25.r,
                  ),
                  Text(
                    isMoveCanDelete() ? Ls.releaseToDelete : Ls.dragToDelete,
                    style: TextStyle(color: Colors.white, fontSize: 13.sp),
                  ),
                ],
              ),
            ),
          )
      ],
    );
  }
}

class AddImageItemView extends StatelessWidget {
  const AddImageItemView({
    super.key,
    required this.onTap,
  });
  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        decoration: BoxDecoration(
          border: Border.all(color: ITheme.borderColor),
        ),
        alignment: Alignment.center,
        child: Icon(
          Icons.photo_camera,
          size: 30.r,
        ),
      ),
    );
  }
}

class ImageItemView extends StatefulWidget {
  const ImageItemView({
    super.key,
    required this.media,
    required this.onTap,
  });
  final MediaModel media;
  final VoidCallback onTap;

  @override
  State<ImageItemView> createState() => _ImageItemViewState();
}

class _ImageItemViewState extends State<ImageItemView> {
  late final key = GlobalKey();
  @override
  void initState() {
    super.initState();
    widget.media.key = key;
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      key: key,
      onTap: widget.onTap,
      child: Image.file(
        File(widget.media.media.thumbPath!),
        fit: BoxFit.cover,
      ),
    );
  }
}

class MediaModel {
  Media media;
  GlobalKey? key;

  Rect? _rect;

  Rect get rect {
    if (_rect == null) {
      final box = key?.currentContext?.findRenderObject() as RenderBox?;
      if (box == null) {
        return Rect.zero;
      }

      final orgin = box.localToGlobal(Offset.zero);
      _rect =
          Rect.fromLTWH(orgin.dx, orgin.dy, box.size.width, box.size.height);
    }

    return _rect ?? Rect.zero;
  }

  MediaModel({
    required this.media,
  });
}
